package com.fan.springboot_websocket;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description:
 * @Author: Fan
 * @Date: 2021/10/12 22:49
 * @Version 1.0
 **/
@ServerEndpoint(value = "/serial")
@Component
public class MyWebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyWebSocketServer.class);

    private static AtomicInteger clientCount = new AtomicInteger(0);

    private static ConcurrentHashMap<String, Session> clientSessionMap = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session ){
        clientSessionMap.put(session.getId(), session);
        clientCount.incrementAndGet();
        sengMsgToAllClient("welcome to server!!!");
        LOGGER.info("新客户端【{}】连接", session.getId());
        LOGGER.info("客户端连接总数：{}", clientCount.get());
    }

    @OnMessage
    public void onMessage(String msg, Session session) {
        LOGGER.info("接受到客户端【{}】消息：{}", session.getId(), msg);
    }

    @OnClose
    public void onClose(Session session) {
        clientSessionMap.remove(session.getId());
        clientCount.decrementAndGet();
        LOGGER.info("客户端【{}】断开连接", session.getId());
        LOGGER.info("当前已连接总数：", clientCount.get());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        LOGGER.error("客户端【{}】连接发生错误：{}", session.getId(), throwable.toString());
    }

    /**
     * 给客户端发送消息
     * @param session
     * @param message
     */
    public void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        LOGGER.info("给客户端【{}】发送消息：{}", session.getId(), message);
    }

    /**
     * 给单个客户端发送消息
     * @param session
     * @param message
     */
    public void sengMsgToSingleClient(Session session, String message) {
        if (session != null && clientSessionMap.get(session.getId()) != null) {
            sendMessage(session, message);
        }
    }

    /**
     * 给所有客户端发送消息
     * @param message
     */
    public void sengMsgToAllClient(String message) {
        for (Session session : clientSessionMap.values()) {
            sendMessage(session, message);
        }
    }
}
